<?php
/**
 * @description: 数据库备份与还原
 * @author     : Geomen
 * @time       : 2018/4/24 10:31
 */


namespace App\Http\Controllers;


use App\Component\CustomHelper;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

class BackupController extends Controller
{
    /**
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->isMethod('post')){
            $fileSys = new Filesystem();
            $files = $fileSys->files(storage_path('app/backups'));
            $data = array();
            foreach ($files as $key=>$file){
                $item['fileName'] = $file->getFilename();
                $item['fileSize'] = CustomHelper::formatFileSize($file->getSize());
                $item['lastModify'] = date('Y-m-d H:i:s',$file->getMTime());
                $data[] = $item;
            }
            $collection = collect($data);
            $sorted = $collection->sortByDesc('lastModify');
            $data = $sorted->values()->all();
            $perPage = 15;
            $page = intval($request->input('page',1));
            $offset = ($page * $perPage) - $perPage;
            $pageData = array_slice($data,$offset,$perPage);
            $list = new LengthAwarePaginator($pageData,count($data),$perPage,$page);
            return response()->json(['r' => 1000, 'i' => $list]);
        }
        return view('other.dbBackup');
    }

    /**
     * 开始备份操作
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request)
    {
//         $result = \Artisan::call('backup:mysql-dump');
        $result = CustomHelper::backupsDb();
        return response()->json(['r' => 1000, 'i' => $result]);
    }

    /**
     * 还原备份
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function restore(Request $request)
    {
        $filename = e($request->input('filename'));
        $result = CustomHelper::restoreDb($filename);
        return response()->json(['r' => 1000, 'i' => $result]);
    }

    /**
     * 还原备份
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function del(Request $request)
    {
        $filename = e($request->input('filename'));
        $file = storage_path('app/backups/'.$filename);
        $File = new Filesystem();
        if ($File->exists($file)){
            $File->delete($file);
            return response()->json(['r' => 1000, 'i' => '删除成功','status' => 'success']);
        }else{
            return response()->json(['r' => 2000, 'i' => '文件不存在','status' => 'fail']);
        }

    }
}